package com.gxa.day2022_08_09_28.emp_dept_system.utils;

import com.mysql.cj.jdbc.Driver;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 工具代码 ，一般都是静态方法
 */
public class DBConnection {

    //一般会放到一个properties文件中
    private static String URL;
    private static String USER_NAME;
    private static String PASSWORD;

    static {
        try {
            InputStream inputStream = DBConnection.class.getClassLoader().getResourceAsStream("com/gxa/day2022_08_09_28/emp_dept_system/db.properties");
            Properties properties = new Properties();
            properties.load(inputStream);

            URL = properties.getProperty("jdbc.url");
            USER_NAME = properties.getProperty("jdbc.username");
            PASSWORD = properties.getProperty("jdbc.password");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取connection
     * @return
     */
    public static Connection getConnection(){

        //1、注册驱动
        try {
            DriverManager.registerDriver(new Driver());
            //2、获取连接
            Connection connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);

            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * 关闭资源
     * @param ps
     * @param connection
     */
    public static void close(PreparedStatement ps,Connection connection){
        try {
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭资源
     * @param rs
     * @param ps
     * @param connection
     */
    public static void close(ResultSet rs,PreparedStatement ps, Connection connection){
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        close(ps,connection);
    }
}
